var that = '';
const FileSystemManeger = wx.getFileSystemManager()
Page({
  data: {
    top_img:["https://pic.imgdb.cn/item/63a7fcac08b6830163e9eebb.png","https://pic.imgdb.cn/item/63a7fcac08b6830163e9eec9.png"],
    flag:true,
    transform:false,
    current:0,
    title:"动物识别",
    guide:"地球上的纯种狗狗我都认得了，发我一张试试吧~",
    imgB64: '',
    imgB641:"",
    loading:true,
    loadingTip:"页面正在加载"
  },
  open_menu(){
    if(this.data.transform == false){
      this.setData({
        transform : true
      })
    }else{
      this.setData({
        transform:false
      })
    }
  },
  end_change(e){
    var title = ["动物识别","植物识别"]
    var guide = ["地球上的纯种狗狗我都认得了，发我一张试试吧~","遇到不认识的植物怎么办，快来搜搜看~"]
    var id = e.detail.current
    switch(id){
      case 0:
        this.setData({
          title:title[0],
          guide:guide[0]
        })
        break
      case 1:
        this.setData({
          title:title[1],
          guide:guide[1]
        })
        break
    }
  },
  onLoad(options) {
    that = this;
    wx.showLoading({
      title: '加载中~',
      mask:"true"
    })
    setTimeout(function () {
      that.setData({
        loading:false
      })
      wx.hideLoading()
    }, 2000)
  },

  // 以下是植物识别
  chooseimgTap: function () {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths[0];
        that.getB64ByUrl(tempFilePaths);
        that.setData({
          img: tempFilePaths
        });
        wx.showLoading({
          title: '正在识别中~',
          mask:true,
          success:res=>{
            console.log(res)
            // that.plantTap()
          },
          fail:err=>{
            console.log(err)
          }
        })
        setTimeout(function () {
          that.plantTap()
          wx.hideLoading()
        }, 3000)

      }
    })
  },
  getB64ByUrl: function (url) {
    console.log(url)
    const FileSystemManager = wx.getFileSystemManager();
    FileSystemManager.readFile({
      filePath: url,
      encoding: 'base64',
      success(res) {
        // console.log(res.data);
        that.setData({
          imgB64: res.data
        });
      }
    })
  },
  /**
   * 识别
   */
  plantTap: function (e) {
    const imgB64 = that.data.imgB64;
    if (!imgB64) {
      that.setData({
        ishow: true
      });
      return;
    };

    wx.showLoading({
      title: '识别中',
    })

    setTimeout(function () {
      wx.hideLoading()
    }, 300)



    that.getToken(function (token) {
      that.getResult(token);
    });
  },
  getToken: function (callback) {
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=FT6vzMxsZEgdIAwa6CkEIPIK&client_secret=CBrtoKUsQBwL23e12tWztGmntj0mevoZ',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        var token = res.data.access_token;
        console.log(token);
        return callback(token);
      }
    });
  },
  getResult: function (token) {
    wx.request({
      url: 'https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token=' + token,
      method: "post",
      data: {
        image: that.data.imgB64,
        baike_num:10,
      },

      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        console.log(res)
        if(res.data.result[0].name == "非植物"){
          wx.showModal({
            showCancel:false,
            confirmText:"确定",
            content:"此识别结果为非植物，请重新上传照片~"
          })
        }else{
          var name = []
          var num = []
          var score = []
          var baidu_image = []
          var introduce = res.data.result[0].baike_info.description
          var baidu_url = []
          for (let index = 0; index < res.data.result.length; index++) {
            name.push(res.data.result[index].name)
            num.push(res.data.result[index].score)
            baidu_image.push(res.data.result[index].baike_info.image_url)
            baidu_url.push(res.data.result[index].baike_info.baike_url)
          }
          for (let j = 0; j < num.length; j++) {
            score.push(100*num[j].toFixed(2))
          }
          var name_1 = JSON.stringify(name)
          var score_1 = JSON.stringify(score)
          var baidu_image1 = JSON.stringify(baidu_image)
          var introduce1 = JSON.stringify(introduce)
          var user_img = that.data.img
          var baidu_url_1 = JSON.stringify(baidu_url)
          wx.navigateTo({
            url: '/pages/result/result?name='+name_1 + '&score='+ score_1 + '&baidu_image=' + baidu_image1 + '&introduce=' + introduce1 + '&class1='+"植物百科"+ "&user_img=" + user_img + '&baidu_url='+ baidu_url_1
          })
        }
      }
    });
  },

  // 以下是动物的鉴别
  chooseimgTap1: function () {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths[0];
        that.getB64ByUrl1(tempFilePaths);
        that.setData({
          img: tempFilePaths
        });
        wx.showLoading({
          title: '正在识别中~',
          mask:true,
          success:res=>{
            console.log(res)
            // that.plantTap()
          },
          fail:err=>{
            console.log(err)
          }
        })
        setTimeout(function () {
          that.plantTap1()
          wx.hideLoading()
        }, 3000)

      }
    })
  },
  getB64ByUrl1: function (url) {
    console.log(url)
    const FileSystemManager = wx.getFileSystemManager();
    FileSystemManager.readFile({
      filePath: url,
      encoding: 'base64',
      success(res) {
        // console.log(res.data);
        that.setData({
          imgB641: res.data
        });
      }
    })
  },
  /**
   * 识别
   */
  plantTap1: function (e) {
    const imgB64 = that.data.imgB641;
    if (!imgB64) {
      that.setData({
        ishow: true
      });
      return;
    };

    wx.showLoading({
      title: '识别中',
    })

    setTimeout(function () {
      wx.hideLoading()
    }, 300)



    that.getToken(function (token) {
      that.getResult1(token);
    });
  },
  getResult1: function (token) {
    wx.request({
      url: 'https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token=' + token,
      method: "post",
      data: {
        image: that.data.imgB641,
        baike_num:5,
        top_num:3
      },

      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        console.log(res)
        if(res.data.result[0].name == "非动物"){
          wx.showModal({
            showCancel:false,
            confirmText:"确定",
            content:"此识别结果为非动物，请重新上传照片~"
          })
        }else{
          var name = []
          var num = []
          var score = []
          var baidu_image = []
          var introduce = res.data.result[0].baike_info.description
          var baidu_url = []
          for (let index = 0; index < res.data.result.length; index++) {
            name.push(res.data.result[index].name)
            num.push(res.data.result[index].score)
            baidu_image.push(res.data.result[index].baike_info.image_url)
            baidu_url.push(res.data.result[index].baike_info.baike_url)
          }
          for (let j = 0; j < num.length; j++) {
            score.push(100*num[j])
          }
          var name_1 = JSON.stringify(name)
          var score_1 = JSON.stringify(score)
          var baidu_image1 = JSON.stringify(baidu_image)
          var introduce1 = JSON.stringify(introduce)
          var baidu_url_1 = JSON.stringify(baidu_url)
          var user_img = that.data.img
          wx.navigateTo({
            url: '/pages/result/result?name='+name_1 + '&score='+ score_1 + '&baidu_image=' + baidu_image1 + '&introduce=' + introduce1 + '&class1='+"动物百科"+ "&user_img=" + user_img + '&baidu_url='+ baidu_url_1
          })
        }
      }
    });
  }
})